# encoding: utf-8
import os
import pathlib
import shutil

from automatic.file.FolderCompareListener import FolderCompareListener
from automatic.file.FolderCompareResultType import FOLDER_COMPARE_RESULT_TYPE_DIFFERENT_FILE, \
    FOLDER_COMPARE_RESULT_TYPE_NEW_ONLY


class FolderCompareUpdateFileGenerator(FolderCompareListener):

    file_object = None

    def __init__(self, output_dir, new_dir):
        self.new_dir = new_dir
        self.output_dir = output_dir

    def mkdir_parent(self, path):
        np = pathlib.Path(path)
        if not np.parent.exists():
            np.parent.mkdir(parents=True)

    def process(self, result_type, new_root_dir, new_relative_dir, old_root_dir, old_relative_dir, file_name):

        new_sub_path = (new_relative_dir+os.sep+file_name)if len(new_relative_dir) else file_name

        if result_type == FOLDER_COMPARE_RESULT_TYPE_DIFFERENT_FILE:
            new_path = self.output_dir + new_sub_path
            self.mkdir_parent(new_path)
            shutil.copy(new_root_dir+new_sub_path, new_path)
        elif result_type == FOLDER_COMPARE_RESULT_TYPE_NEW_ONLY:
            new_path = pathlib.Path(new_root_dir + new_sub_path)
            np = self.output_dir + new_sub_path
            self.mkdir_parent(np)
            if new_path.is_dir():
                shutil.copytree(new_root_dir+new_sub_path, np)
            else:
                shutil.copy(new_root_dir + new_sub_path, np)
        else:
            pass